package cn.bugstack.mybatis.bindings;

import cn.bugstack.mybatis.mapping.MappedStatement;
import cn.bugstack.mybatis.mapping.SqlCommandType;
import cn.bugstack.mybatis.session.Configuration;
import cn.bugstack.mybatis.session.SqlSession;

import java.lang.reflect.Method;

/**
 * 包装mapper接口中的某个方法
 */
public class MapperMethod {

    private final SqlCommand command;

    public MapperMethod(Configuration configuration, Class<?> mapperInterface, Method method) {
        this.command = new SqlCommand(configuration, mapperInterface, method);
    }


    /**
     * 执行mapper接口的方法，就是调用sqlSession的相应方法
     * @param sqlSession
     * @param args
     * @return
     */
    public Object execute(SqlSession sqlSession, Object[] args) throws Exception {
        Object result = null;
        switch (command.type) {
            case DELETE:
                break;
            case INSERT:
                break;
            case SELECT:
                result =  sqlSession.selectOne(command.name, args);
                break;
            case UPDATE:
                break;
            default:
                throw new RuntimeException("Unknown mapper method for : "+ command.name);
        }
        return result;
    }

    /**
     * 将mapper接口的方法和sql指令类型绑定
     */
    public static class SqlCommand {

        private final String name;
        private final SqlCommandType type;

        public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
            String statementName = mapperInterface.getName() + "." + method.getName();
            MappedStatement ms = configuration.getMappedStatement(statementName);
            name = ms.getId();
            type = ms.getSqlCommandType();
        }

        public String getName() {
            return name;
        }

        public SqlCommandType getType() {
            return type;
        }
    }
}
